//
//  YLRefresh.swift
//  Swift-Codedase
//
//  Created by xyanl on 2023/9/11.
//

import UIKit
import Foundation
import MJRefresh


private struct AssociatedKeys {
    static var RefreshHandlerKey: Void?// = "RefreshHandlerKey"
    static var LoadMoreHandlerKey: Void?// = "LoadMoreHandlerKey"
}

/// 样式
enum RefreshStyle {
    /// 普通
    case normal
    /// gif图
    case gif 
}

extension UITableView {
    
    typealias RefreshHandler = (() -> Void)
    typealias LoadMoreHandler = (() -> Void)
    
    var refreshBlock: RefreshHandler {
        get {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.RefreshHandlerKey) { $0 }
            return objc_getAssociatedObject(self, key) as! RefreshHandler
        }
        set {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.RefreshHandlerKey) { $0 }
            objc_setAssociatedObject(self, key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    
    var loadMoreBlock: LoadMoreHandler {
        get {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.LoadMoreHandlerKey) { $0 }
            return objc_getAssociatedObject(self, key) as! LoadMoreHandler
        }
        set {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.LoadMoreHandlerKey) { $0 }
            objc_setAssociatedObject(self, key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    
    
    /// 下拉刷新
    /// - Parameters:
    ///   - style: 样式
    ///   - completionHandler: 刷新回调
    func headerRefresh(style: RefreshStyle = .normal, _ completionHandler: @escaping RefreshHandler) {
        refreshBlock = completionHandler
        
        switch style {
        case .normal:
            mj_header = YLRefreshHeader(refreshingBlock: { [self] in 
                refreshBlock()
            })
        case .gif:
//            mj_header = YLRefreshGifHeader(refreshingBlock: { [self] in 
//                refreshBlock()
//            })
            mj_header = YLRefreshHeader(refreshingBlock: { [self] in
                refreshBlock()
            })
        }
    }
    
    
    /// 动图加载更多
    /// - Parameters:
    ///   - isAuto: 是否自动刷新
    ///   - completionHandler: 刷新回调
    func footerGifRefresh(isAuto: Bool = false, _ completionHandler: @escaping LoadMoreHandler) {
        footerRefresh(isAuto: isAuto, style: .gif, completionHandler)
    }
    
    
    /// 加载更多
    /// - Parameters:
    ///   - isAuto: 是否自动刷新
    ///   - style: 样式
    ///   - completionHandler: 刷新回调
    func footerRefresh(isAuto: Bool = false, style: RefreshStyle = .normal, _ completionHandler: @escaping LoadMoreHandler) {
        loadMoreBlock = completionHandler
        
        if isAuto == true && style == .normal {
            let footer = YLRefreshAutoFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
            // 当底部控件出现多少时就自动刷新(默认为1.0， 也就是底部控件完全出现时，才会自动刷新)
            footer.triggerAutomaticallyRefreshPercent = 0.5 //-20
            mj_footer = footer
        } else if isAuto == true && style == .gif {
            let footer = YLRefreshAutoGifFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
            // 当底部控件出现多少时就自动刷新(默认为1.0， 也就是底部控件完全出现时，才会自动刷新)
            footer.triggerAutomaticallyRefreshPercent = 0.5 //-20
            mj_footer = footer
        } else if isAuto == false && style == .normal {
            mj_footer = YLRefreshBackFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
        } else if isAuto == false && style == .gif {
            mj_footer = YLRefreshGifFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
        }
    }
    
    
    /// 开始刷新
    func beginRefreshing() {
        DispatchQueue.main.async {
            self.mj_header?.beginRefreshing() 
        }
    }
    
    /// 结束刷新
    func endRefreshing() {
        DispatchQueue.main.async {
            self.mj_header?.endRefreshing()
            self.mj_footer?.endRefreshing() 
        }
    }
    
    /// 没有更多数据
    func endRefreshingWithNoMoreData() {
        DispatchQueue.main.async {
            self.mj_footer?.endRefreshingWithNoMoreData() 
        }
    }
    
}

extension UICollectionView {
    
    typealias RefreshHandler = (() -> Void)
    typealias LoadMoreHandler = (() -> Void)
    
    var refreshBlock: RefreshHandler {
        get {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.RefreshHandlerKey) { $0 }
            return objc_getAssociatedObject(self, key) as! RefreshHandler
        }
        set {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.RefreshHandlerKey) { $0 }
            objc_setAssociatedObject(self, key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    
    var loadMoreBlock: LoadMoreHandler {
        get {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.LoadMoreHandlerKey) { $0 }
            return objc_getAssociatedObject(self, key) as! LoadMoreHandler
        }
        set {
            let key: UnsafePointer = withUnsafePointer(to: &AssociatedKeys.LoadMoreHandlerKey) { $0 }
            objc_setAssociatedObject(self, key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    
    
    /// 下拉刷新
    /// - Parameters:
    ///   - style: 样式
    ///   - completionHandler: 刷新回调
    func headerRefresh(style: RefreshStyle = .normal, _ completionHandler: @escaping RefreshHandler) {
        refreshBlock = completionHandler
        
        switch style {
        case .normal:
            mj_header = YLRefreshHeader(refreshingBlock: { [self] in 
                refreshBlock()
            })
            
        case .gif:
//            mj_header = YLRefreshGifHeader(refreshingBlock: { [self] in 
//                refreshBlock()
//            })
            mj_header = YLRefreshHeader(refreshingBlock: { [self] in
                refreshBlock()
            })
        }
    }
    
    
    /// 动图加载更多
    /// - Parameters:
    ///   - isAuto: 是否自动刷新
    ///   - completionHandler: 刷新回调
    func footerGifRefresh(isAuto: Bool = false, _ completionHandler: @escaping LoadMoreHandler) {
        footerRefresh(isAuto: isAuto, style: .gif, completionHandler)
    }
    
    
    /// 加载更多
    /// - Parameters:
    ///   - isAuto: 是否自动刷新
    ///   - style: 样式
    ///   - completionHandler: 刷新回调
    func footerRefresh(isAuto: Bool = false, style: RefreshStyle = .normal, _ completionHandler: @escaping LoadMoreHandler) {
        loadMoreBlock = completionHandler
        
        if isAuto == true && style == .normal {
            let footer = YLRefreshAutoFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
            // 当底部控件出现多少时就自动刷新(默认为1.0， 也就是底部控件完全出现时，才会自动刷新)
            footer.triggerAutomaticallyRefreshPercent = 0.5 //-20
            mj_footer = footer
        } else if isAuto == true && style == .gif {
            let footer = YLRefreshAutoGifFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
            // 当底部控件出现多少时就自动刷新(默认为1.0， 也就是底部控件完全出现时，才会自动刷新)
            footer.triggerAutomaticallyRefreshPercent = 0.5 //-20
            mj_footer = footer
        } else if isAuto == false && style == .normal {
            mj_footer = YLRefreshBackFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
        } else if isAuto == false && style == .gif {
            mj_footer = YLRefreshGifFooter(refreshingBlock: { [self] in 
                loadMoreBlock()
            })
        }
    }
    
    
    /// 开始刷新
    func beginRefreshing() {
        DispatchQueue.main.async {
            self.mj_header?.beginRefreshing() 
        }
    }
    
    /// 结束刷新
    func endRefreshing() {
        DispatchQueue.main.async {
            self.mj_header?.endRefreshing()
            self.mj_footer?.endRefreshing() 
        }
    }
    
    /// 没有更多数据
    func endRefreshingWithNoMoreData() {
        DispatchQueue.main.async {
            self.mj_footer?.endRefreshingWithNoMoreData() 
        }
    }
    
}
